﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using HYView;
using ModelValidation.FireCompartment;

namespace ModelValidation.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdFireAreaOutlineCheck : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			CmdViewType types = CmdViewType.AreaPlan;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Transaction transaction = null;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				transaction = new Transaction(cmdData.Application.ActiveUIDocument.Document);
				transaction.Start("FireAreaOutlineWinDoorWallCheck");
				transaction.Commit();
				DlgSelectFireDefAreaView dlgSelectFireDefAreaView = new DlgSelectFireDefAreaView(cmdData);
				if (dlgSelectFireDefAreaView.IsDlgValid && dlgSelectFireDefAreaView.ShowDialog() != DialogResult.OK)
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					List<ViewPlan> list = dlgSelectFireDefAreaView.SelectedViews();
					if (list.Count == 0)
					{
						result = Autodesk.Revit.UI.Result.Cancelled;
					}
					else
					{
						DlgFireOutlineWinDoorWallCheck dlgFireOutlineWinDoorWallCheck = null;
						try
						{
							WindowHandle windowHandle = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
							ModelessFormApp.m_appThis.ShowForm(cmdData, list);
							int wMsg = 7;
							CmdFireAreaOutlineCheck.SendMessage(windowHandle.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
						}
						catch
						{
							if (dlgFireOutlineWinDoorWallCheck != null)
							{
								dlgFireOutlineWinDoorWallCheck.Close();
							}
							return Autodesk.Revit.UI.Result.Failed;
						}
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}
	}
}
